﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid;
using MicropleSoft.Controls;
using MicropleSoft.Controls.DialogBox;
using MicropleSoft.WmsApp.Base.Business;
using MicropleSoft.WmsApp.Library.Factory;
using MicropleSoft.WmsApp.Library.Proxy;
using MicropleSoft.WmsApp.Library.Security;
using MicropleSoft.WmsApp.Library.ServiceFacade;

namespace MicropleSoft.WmsApp.PurchaseOrder
{
    public class PurchaseOrderBusinessModelControl :
        IBusinessModelControl<PurchaseOrderWrap>
    {
        private const string PoIdPrix = "PO";
        private readonly IDataBinderPanel _dataBinderPanel;
        private readonly ServerProxy _serverProxy = ServerProxyFactory.GetServerProxy();
        private readonly XGridControl _xGridControl;
        private PurchaseOrderWrap _purchaseOrderWrap;

        public PurchaseOrderBusinessModelControl(
            IDataBinderPanel dataBinderPanel,
            XGridControl xGridControl)
        {
            _dataBinderPanel = dataBinderPanel;
            _xGridControl = xGridControl;
            //绑定LookUp
            var gridView = (GridView) _xGridControl.MainView;
            LookUpBind.BindingLookUpEdit4Grid(gridView, gridView.Columns.ColumnByFieldName("Status"),
                                              "PurchaseOrder-Status.xml");
            gridView.Columns.ColumnByFieldName("Status").ColumnEdit.ReadOnly = true;
        }

        #region IBusinessModelControl<PurchaseOrderWrap> Members

        public void DataBind(PurchaseOrderWrap t, IDataBinderPanel dataBinderPanel)
        {
            dataBinderPanel.ExecuteDataBind(t.PPurchaseOrder);
        }

        public void DataBind(PurchaseOrderWrap t, XGridControl xGridControl)
        {
            xGridControl.DataSource = t.PPurchaseOrderDetails;
            xGridControl.RefreshDataSource();
        }

        public void LoadWrap(string poId)
        {
            var purchaseOrderWrap =
                (PurchaseOrderWrap) _serverProxy.CallService("GetPurchaseOrderWrapByPo", poId, UserSession.CurrentWhId);
            if (purchaseOrderWrap == null)
            {
                throw new Exception("not exist PurchaseOrder!");
            }

            //将purchaseOrderWrap对象中的子对象都执行方法：
            purchaseOrderWrap.PPurchaseOrder.AfterQueryFromServer();
            foreach (var purchaseOrderDetail in purchaseOrderWrap.PPurchaseOrderDetails)
            {
                purchaseOrderDetail.AfterQueryFromServer();
            }

            _purchaseOrderWrap = purchaseOrderWrap;
            DataBind(_purchaseOrderWrap, _dataBinderPanel);
            DataBind(_purchaseOrderWrap, _xGridControl);
        }

        public PurchaseOrderWrap GetCurrentWrap()
        {
            return _purchaseOrderWrap;
        }

        public void SaveWrap(PurchaseOrderWrap wrap)
        {
            try
            {
                if (_purchaseOrderWrap != null)
                {
                    if (_purchaseOrderWrap.PPurchaseOrder.DomainObjectState == DomainEntityState.Added)
                    {
                        //_purchaseOrderWrap.PPurchaseOrder.PoId = GeneratePurchaseOrderPoId();
                        foreach (var purchaseOrderDetail in _purchaseOrderWrap.PPurchaseOrderDetails)
                        {
                            if (purchaseOrderDetail.DomainObjectState == DomainEntityState.Added)
                            {
                                purchaseOrderDetail.PoId = _purchaseOrderWrap.PPurchaseOrder.PoId;
                            }
                        }
                    }
                    else
                    {
                        foreach (var purchaseOrderDetail in _purchaseOrderWrap.PPurchaseOrderDetails)
                        {
                            if (purchaseOrderDetail.DomainObjectState == DomainEntityState.Added)
                            {
                                purchaseOrderDetail.PoId = _purchaseOrderWrap.PPurchaseOrder.PoId;
                            }
                        }
                    }
                    _serverProxy.CallService("SavePurchaseOrderWrap", wrap);
                    wrap.PPurchaseOrder.AcceptChanges();
                    foreach (var orderDetail in wrap.PPurchaseOrderDetails)
                    {
                        orderDetail.AcceptChanges();
                    }
                }
            }
            catch (Exception exception)
            {
                CustomMessageBox.ShowError(exception.Message);
            }
        }

        public void AddDetail()
        {
            if (_purchaseOrderWrap != null)
            {
                var detail = DomainObjectFactory.CreatePurchaseOrderDetail();
                detail.LineId = _purchaseOrderWrap.PPurchaseOrderDetails.Count + 1;
                detail.RowId = GenerateMaxPurchaseOrderDetailRowId();
                detail.WhId = UserSession.CurrentWhId;
                detail.DomainObjectState = DomainEntityState.Added;
                _purchaseOrderWrap.PPurchaseOrderDetails.Add(detail);
                var form = new FormPurchaseOrderDetail(ref detail);
                form.ShowDialog();
                DataBind(_purchaseOrderWrap, _xGridControl);
            }
        }

        public void NewWrap()
        {
            if (_purchaseOrderWrap != null)
            {
                if (_purchaseOrderWrap.IsNeedSaved())
                {
                    var result = CustomMessageBox.ShowOkNoCancel("订单没有保存，请问要保存吗？");
                    if (result == DialogResult.OK)
                    {
                        SaveWrap(_purchaseOrderWrap);
                        DoNewWrap();
                    }
                    else if (result == DialogResult.No)
                    {
                        DoNewWrap();
                    }
                    else
                    {
                        //Cancel，什么都不做。
                    }
                }
            }
            else
            {
                DoNewWrap();
            }
        }

        public string TableName
        {
            get { return "PURCHASE_ORDER"; }
        }

        public string DetailTableName
        {
            get { return "PURCHASE_ORDER_DETAIL"; }
        }

        public string BusinessCode
        {
            get { return "PurchaseOrder"; }
        }

        #endregion

        private string GeneratePurchaseOrderPoId()
        {
            var dateTime = (DateTime) _serverProxy.CallService("GetCurrentDateTime");
            var val = (int) _serverProxy.CallService("GetBillNumber", BusinessCode,
                                                     UserSession.CurrentWhId, dateTime.Year, dateTime.Month, 0);
            var number = "00000" + val;
            var result = PoIdPrix + dateTime.ToString("yyyy") + dateTime.ToString("MM") +
                         number.Substring(number.Length - 5, 5);
            return result;
        }

        private int GenerateMaxPurchaseOrderRowId()
        {
            return (int) _serverProxy.CallService("GetMaxValue", TableName);
        }

        private int GenerateMaxPurchaseOrderDetailRowId()
        {
            return (int) _serverProxy.CallService("GetMaxValue", DetailTableName);
        }

        private void DoNewWrap()
        {
            _purchaseOrderWrap = new PurchaseOrderWrap();
            _purchaseOrderWrap.PPurchaseOrder = DomainObjectFactory.CreatePurchaseOrder();
            _purchaseOrderWrap.PPurchaseOrder.DomainObjectState = DomainEntityState.Added;
            _purchaseOrderWrap.PPurchaseOrder.RowId = GenerateMaxPurchaseOrderRowId();
            _purchaseOrderWrap.PPurchaseOrder.PoId = GeneratePurchaseOrderPoId();
            _purchaseOrderWrap.PPurchaseOrderDetails = new List<PurchaseOrderDetail>();
            DataBind(_purchaseOrderWrap, _dataBinderPanel);
            DataBind(_purchaseOrderWrap, _xGridControl);
        }

        public void EditDetail()
        {
            var gridView = (GridView) _xGridControl.MainView;
            var selectRow = (PurchaseOrderDetail)gridView.GetRow(gridView.FocusedRowHandle);
            if(selectRow != null)
            {
                var form = new FormPurchaseOrderDetail(ref selectRow);
                form.ShowDialog();
                this._xGridControl.RefreshDataSource();
            }
        }
    }
}